<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Version 4 UUID Test / UUID.js</title>
    <script type="text/javascript" src="../src/uuid.js"></script>
  </head>
  <body>
    <h1>Version 4 UUID Test / UUID.js</h1>
    <script type="text/javascript">
      // <![CDATA[
      var n = 128;
      var pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;

      var messages = [];
      var uuids = new Array(n * 2);

      // loop to cover two tests: UUID.generate() and UUID.genV4()
      for (var test = 0; test < 2; test++) {
        var counts = new Array(128);
        for (var i = 0; i < counts.length; i++) { counts[i] = 0; }

        // loop to generate n UUIDs
        for (var i = 0; i < n; i++) {
          var uuid = uuids[test * n + i] = test ? UUID.generate() : String(UUID.genV4());

          if (!pattern.test(uuid)) {
            messages.push("Invalid format\t" + uuid);
          }

          // loop to count each bit's '1'
          for (var sp = 0, np = 0, len = uuid.length; sp < len; sp++) {
            var nibble = parseInt(uuid.charAt(sp), 16);
            if (!isNaN(nibble)) {
              (nibble & 1) && counts[np * 4 + 3]++;
              (nibble & 2) && counts[np * 4 + 2]++;
              (nibble & 4) && counts[np * 4 + 1]++;
              (nibble & 8) && counts[np * 4 + 0]++;
              np++;
            }
          }
        }

        messages.push("Each bit's count of '1' appearing among " + n + " UUIDs:");
        messages.push("\t" + (n / 2) + " is expected for all bits but the variant bits and the version bits.");
        messages.push("Octet\t\tMsb0\tMsb1\tMsb2\tMsb3\tMsb4\tMsb5\tMsb6\tMsb7");
        for (var j = 0, len = counts.length / 8; j < len; j++) {
          messages.push("Octet" + j + "\t\t" + counts.slice(j * 8, (j + 1) * 8).join("\t"));
        }
        if (counts[64] != n || counts[65] != 0) {
          messages.push("Invalid variant bits.");
        }
        if (counts[48] != 0 || counts[49] != n || counts[50] != 0 || counts[51] != 0) {
          messages.push("Invalid version bits.");
        }
        messages.push("");
      }
      // ]]>
    </script>
    <h2>Test Messages</h2>
    <pre><script type="text/javascript">document.writeln(messages.join("\n"));</script></pre>
    <h2>Generated UUIDs</h2>
    <pre><script type="text/javascript">document.writeln(uuids.join("\n"));</script></pre>
  </body>
</html>
